//+build ignore

package main

import (
	"container/list"
	"fmt"
	"strconv"
)

type Student struct {
	Name    string
	Age     uint
	Address string
	Remark  string
	Date    string
}

func main() {

	path := "/tmp/测试用的go.xlsx"
	arr := [...]string{"姓名", "年龄", "地址", "备注", "日期"}

	// var s1 Student
	//fmt.Println(s0)

	_list := list.New()
	var s0 = mockStudent()
	_list.PushBack(s0)
	_list.PushBack(s0)
	_list.PushBack(s0)
	_list.PushBack(s0)
	CreateExcel(_list, &arr, path)

}

func mockStudent() *Student {

	var s2 *Student = &Student{}
	s2.Name = "小明"
	s2.Age = 10
	s2.Address = "小明的地址"
	s2.Remark = "小明的备注"
	s2.Date = "小明的日期"

	return s2
}

const EXCEL_HEAD_CACHE_LEN = 52

var EXCEL_HEAD_ARR = [EXCEL_HEAD_CACHE_LEN]string{"A1", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1", "J1", "K1", "L1", "M1", "N1",
	"O1", "P1", "Q1", "R1", "S1", "T1", "U1", "V1", "W1", "X1", "Y1", "Z1", "AA1", "AB1", "AC1", "AD1",
	"AE1", "AF1", "AG1", "AH1", "AI1", "AJ1", "AK1", "AL1", "AM1", "AN1", "AO1", "AP1", "AQ1", "AR1",
	"AS1", "AT1", "AU1", "AV1", "AW1", "AX1", "AY1", "AZ1"}

var EXCEL_HEAD = [EXCEL_HEAD_CACHE_LEN]string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
	"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ",
	"AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ"}

func CreateExcel(_list *list.List, arr *[5]string, path string) {

	f := excelize.NewFile()
	// 创建一个工作表
	const SHEET1 = "学生信息统计"
	//index := f.NewSheet(SHEET1)
	f.SetSheetName("Sheet1", SHEET1)

	//设置表头
	len := len(arr)
	if len <= EXCEL_HEAD_CACHE_LEN {
		for i := 0; i < len; i++ {
			f.SetCellValue(SHEET1, EXCEL_HEAD_ARR[i], arr[i])
		}
	} else {
		for i := 0; i < EXCEL_HEAD_CACHE_LEN; i++ {
			f.SetCellValue(SHEET1, EXCEL_HEAD_ARR[i], arr[i])
		}
		for i := EXCEL_HEAD_CACHE_LEN; i < len; i++ {
			f.SetCellValue(SHEET1, calcExcelHeadByNum(i), arr[i])
		}
	}

	line := 2
	for i := _list.Front(); i != nil; i = i.Next() {
		// 设置单元格的值
		ss, ok := (i.Value).(*Student)
		//fmt.Println("convert 2 student :", ss, ok)
		if ok {
			f.SetCellValue(SHEET1, EXCEL_HEAD[0]+strconv.Itoa(0+line), ss.Name)
			f.SetCellValue(SHEET1, EXCEL_HEAD[1]+strconv.Itoa(0+line), ss.Age)
			f.SetCellValue(SHEET1, EXCEL_HEAD[2]+strconv.Itoa(0+line), ss.Address)
			f.SetCellValue(SHEET1, EXCEL_HEAD[3]+strconv.Itoa(0+line), ss.Remark)
			f.SetCellValue(SHEET1, EXCEL_HEAD[4]+strconv.Itoa(0+line), ss.Date)
			line++
		}

	}
	// 设置工作簿的默认工作表
	f.SetActiveSheet(0)
	// 根据指定路径保存文件
	if err := f.SaveAs(path); err != nil {
		fmt.Println(err)
	}
}

//计算数字对应的Excel表头的字母 从0开始
func calcExcelHeadByNum(n int) string {

	if n < EXCEL_HEAD_CACHE_LEN {
		return EXCEL_HEAD[n]
	}
	const LEN = len(EXCEL_HEAD)
	var res string
	for {
		if n <= 0 {
			break
		}
		res = EXCEL_HEAD[n-1] + res
		n = (n - 1) / LEN
	}
	return res
}
